﻿using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Ymca.DataAccess.Interfaces;
using Ymca.Entities;
using Ymca.Web.Models.Profile;
using Ymca.Web.Services.Interfaces;

namespace Ymca.Web.Controllers
{
	[Authorize]
    public class UserProfileController : Controller
    {
		private IUnityContainer _container;
		private IUserProfileService _userService;

		public UserProfileController()
		{
			_container = ContainerConfig.Container;
			_userService = _container.Resolve<IUserProfileService>();
		}

		[HttpGet]
		[AllowAnonymous]
        public ActionResult Index(string id)
        {
			if (string.IsNullOrEmpty(id))
			{
				return HttpNotFound();
			}
			UserProfile profile = _userService.GetProfile(id);
			IndexViewModel viewModel = new IndexViewModel(profile);
            return View(viewModel);
        }

		[HttpGet]
		public ActionResult Edit(string returnUrl)
		{
			UserProfile profile = _userService.GetProfile(User.Identity.Name);
			EditProfileViewModel viewModel = new EditProfileViewModel(profile);
			ViewBag.ReturnUrl = returnUrl;
			return View(viewModel);
		}

		[HttpPost]
		public ActionResult Edit(EditProfileViewModel viewModel, string returnUrl)
		{
			if (ModelState.IsValid)
			{
				MembershipUser user = Membership.GetUser(User.Identity.Name);
				if (!user.UserName.Equals(viewModel.Id))
				{
					//TODO: Verify new username is available
				}
				if (!user.Email.Equals(viewModel.Email))
				{
					if (Membership.FindUsersByEmail(viewModel.Email).Count > 0)
					{
						ModelState.AddModelError(string.Empty, "User with email " + viewModel.Email + " is already exist");
						return View(viewModel);
					}
				}

				_userService.EditProfile(viewModel);

				if (!string.IsNullOrEmpty(returnUrl))
				{
					return Redirect(returnUrl);
				}
				return RedirectToAction("Index", "Home");
			}
			return View(viewModel);
		}
    }
}
